package com.superjson.showpro.service.impl;

import com.superjson.showpro.base.GenericServiceImpl;
import com.superjson.showpro.dao.EvaluateDao;
import com.superjson.showpro.entity.ArticleCatalog;
import com.superjson.showpro.entity.Evaluate;
import com.superjson.showpro.service.ArticleCatalogService;
import com.superjson.showpro.service.EvaluateService;
import com.superjson.showpro.shared.enums.EvaluateResultEnum;
import com.superjson.showpro.shared.result.Result;
import com.superjson.showpro.shared.result.ResultUtil;
import com.superjson.showpro.shared.util.IpUtill;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

import static com.beantools.util.ObjectUtil.isNotNull;
import static com.superjson.showpro.shared.util.CommonUtil.ifNullThrow;

@Service
public class EvaluateServiceImpl extends GenericServiceImpl<Evaluate> implements EvaluateService {

    private EvaluateDao evaluateDao;
    @Autowired
    private ArticleCatalogService articleCatalogService;

    @Autowired
    public EvaluateServiceImpl(EvaluateDao evaluateDao) {
        super(evaluateDao);
        this.evaluateDao = evaluateDao;
    }

    @Override
    public Result saveEvaluate(HttpServletRequest request, Long articleId, EvaluateResultEnum resultEnum) {
        ArticleCatalog catalog = articleCatalogService.get(articleId).getResultData();
        ifNullThrow(catalog, "文章不存在");
        String ip = IpUtill.getIpAddr(request);
        String token = request.getSession().getId();
        Evaluate dbEvaluate = evaluateDao.getByTokenIp(articleId, ip);
        dbEvaluate = isNotNull(dbEvaluate) ? dbEvaluate : new Evaluate();
        dbEvaluate.setArticleCatalog(catalog);
        dbEvaluate.setEvaluateResult(resultEnum);
        dbEvaluate.setIp(ip);
        dbEvaluate.setToken(token);
        evaluateDao.save(dbEvaluate);
        return ResultUtil.buildSuccess();
    }

    @Override
    public Result<Evaluate> getByTokenIp(Long articleId, String ip) {
        return ResultUtil.buildSuccess(evaluateDao.getByTokenIp(articleId, ip));
    }
}